package com.example.demo.controller;

import com.example.demo.pojo.Account;
import com.example.demo.service.AccountService;
import com.example.demo.service.StatsService;
import com.example.demo.utils.CaptchaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController {
    private static final String ERROR_MESSAGES = "errorMessages";
    private static final String RANDOM_CODE_KEY = "RANDOMCODEKEY";

    @Autowired
    private AccountService accountService;

    @Autowired
    private StatsService statsService;

    @RequestMapping("/login")
    public String toLogin(Account account) {

        return "/sign-in";
    }

    @RequestMapping("/signup")
    public String toSignUp(Account account) {

        return "/sign-up";
    }

    /**
     * @TODO 添加验证码效验
     * @param account
     * @return
     */
    @RequestMapping("/checkAccount")
    public String login(Account account, Model model, String verifyCode, HttpServletRequest request) {

        String msg;
        String realCode = (String) request.getSession().getAttribute(RANDOM_CODE_KEY);
        boolean validate = CaptchaUtils.validate(realCode, verifyCode);
        if (!validate) {
            msg = "验证码错误";
            model.addAttribute(ERROR_MESSAGES, msg);
            return "/sign-in";
        }
        String username = account.getUsername();
        String password = account.getPassword();
        boolean b = accountService.searchAccountByUserNameAndPassword(username, password);
        if (b) {

            statsService.addStats(username);
            request.getSession().setAttribute("username_login", username);
            request.getSession().setAttribute("password_login", password);
            return "redirect:/home/main";
        } else {
            msg = "用户名或者密码错误";
            model.addAttribute(ERROR_MESSAGES, msg);
            return "/sign-in";
        }
    }
}
